//
// Created by fang on 20-5-5.
//

#include <evdns.h>
#include <malloc.h>
#include "segevent.h"

struct event_base *events;
static context** static_context;
static unsigned int static_context_size = 1024 *1024;

/**
 * 初始化event
 */
void seg_init_event() {
    events = event_base_new();
    static_context = (context**)malloc(sizeof(context) * 1024 * 1024);
}

/**
 * 添加事件
 *
 * @param fd
 * @param events
 * @param fn
 * @param data
 */
void seg_event_add(int fd, short events, event_callback_fn fn, void *data) {
    //TODO 预分配内存
    context* c = (context*)malloc(sizeof(context));
    c->fd = fd;
    c->read_buf = NULL;
    c->write_buf = NULL;
    c->writed_len = 0;
    c->data = data;
    c->ev = event_new(events, fd, EV_TIMEOUT|EV_READ|EV_PERSIST|EV_WRITE, fn, c);
    event_add(c->ev, NULL);
}

/**
 * 移除监听事件
 *
 * @param fd
 */
void seg_event_remove(context* c) {
    event_del(c->ev);
    free(c);
}